﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Cinchoo.Core;
using System.Diagnostics;
using Cinchoo.Core.Diagnostics;

namespace ChoWorkflowServer
{
    public static class ChoTaskProcessManager
    {
        #region Shared Data Members (Private)

        public static readonly object SyncRoot = new object();
        private static readonly Dictionary<string, Process> _taskProcessDict = new Dictionary<string, Process>();

        #endregion Shared Data Members (Private)

        #region Shared Members (Public)

        public static void Register(string taskName, Process process)
        {
            ChoGuard.ArgumentNotNullOrEmpty(taskName, "TaskName");

            lock (SyncRoot)
            {
                if (_taskProcessDict.ContainsKey(taskName))
                    _taskProcessDict[taskName] = process;
                else
                    _taskProcessDict.Add(taskName, process);
            }
        }

        public static void Unregister(string taskName)
        {
            ChoGuard.ArgumentNotNullOrEmpty(taskName, "TaskName");

            lock (SyncRoot)
            {
                if (_taskProcessDict.ContainsKey(taskName))
                    _taskProcessDict.Remove(taskName);
            }
        }

        public static bool TryGetProcessId(string taskName, out Process process)
        {
            ChoGuard.ArgumentNotNullOrEmpty(taskName, "TaskName");

            process = null;
            lock (SyncRoot)
            {
                if (_taskProcessDict.ContainsKey(taskName))
                {
                    process = _taskProcessDict[taskName];
                    return true;
                }
                else
                    return false;
            }
        }

        public static void KillTask(string taskName)
        {
            lock (SyncRoot)
            {
                Process process = null;
                if (TryGetProcessId(taskName, out process))
                {
                    if (process != null && !process.HasExited)
                        process.Kill();

                    Unregister(taskName);
                }
            }
        }

        public static void KillAllTasks()
        {
            lock (SyncRoot)
            {
                foreach (Process process in _taskProcessDict.Values.ToArray())
                {
                    if (process != null && !process.HasExited)
                        process.Kill();
                }
            }
        }

        #endregion Shared Members (Public)

    }
}
